/**
 * 创建三维地球
 */
import Tools from "./Tools"
import BmapImageryProvider from "./BmapImageryProvider";
export default class Earth {

    constructor() {

        this.viewer = null;

        this.scene = null;

        this.camera = null;

        this.cesiumToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJhMTlkZGFiZC1jYzkwLTQ2ZmEtYTQ5Ny1mYTczZWQxOGMyOTIiLCJpZCI6NTk2NDEsImlhdCI6MTYyNDM1NDkxMn0.CC1U9xxGZjqHGChTOJ_29-_EVUtMBBxx96CqcRO-Hpg';

        this.tdtToken = [
            '8ae68bd1e4a5a7661e4dd9354d9bb8da',
            'c7a7a9a9c377b2713098f5e5daa191a2',
            '5e7e45178a859cdb1f3600dfbf630714',
            'a552028ca471aa5c82b7451f227256dc',
            '0f08000954340ec8e2618d3d9e8c98ef',
            '14986391ecf73dece97c61fc4f1cadf5',
        ];

        this.mapboxToken = 'sk.eyJ1IjoibG9nMiIsImEiOiJja3ZtZnQ2ejgxaTZ3MnVxZ2l4YzZ4dDZkIn0.TAlHZTwl3oSlBcGxm6r1Ig';
        
        this.Tools = new Tools();
    }

    /**
     * 
     * required dom dom对象
     * @param opt 初始化选项 参照 https://cesium.com/learn/cesiumjs/ref-doc/Viewer.html#.ConstructorOptions
     * @param ak AccessToken
     * @returns 
     */
    init(dom, { opt, ak } = {}) {
        // 定义 opt
        if (this.Tools.nullBool(opt)) {
            opt = {
                shouldAnimate: true,
                animation: false,
                timeline: false,
                geocoder: false,
                homeButton: false,
                sceneModePicker: false,
                baseLayerPicker: false,
                navigationHelpButton: false,
                infoBox: false,
                fullscreenButton: false,
                vrButton: false,
                selectionIndicator: false,
                contextOptions: {
                    webgl: {
                        alpha: true,
                    }
                },
            }
        }

        if (this.Tools.strBool(dom)) {
            return alert('DOM 没有定义');
        }

        // 定义 token
        if (this.Tools.strBool(ak)) {
            ak = this.cesiumToken
        }

        // 设置token
        Cesium.Ion.defaultAccessToken = ak;

        // 初始化 cesium
        this.viewer = new Cesium.Viewer(dom, opt);

        this.camera = this.viewer.camera;

        this.scene = this.viewer.scene;

        return this.viewer
    }

    /**
     * 更换天空盒
     */
    skyBox({ positiveX, negativeX, positiveY, negativeY, positiveZ, negativeZ }) {
        this.scene.skyBox = new Cesium.SkyBox({
            sources: {
                positiveX,
                negativeX,
                positiveY,
                negativeY,
                positiveZ,
                negativeZ
            }
        })
    }

    /**
     * 
     * @required name   底图类型 amap, baidu, tdt, google, arcGis, naturalEarth, qqMap, osm, mapbox
     * @param layer  WMTS请求的层名称 
     *                  天地图：img_w cia_w
     * @param style  WMTS请求的样式名称 
     *                  百度：img vec 或者不传
     *                  天地图：layer：
     *                          img_w => img
     *                          cia_w => cia
     *                  腾讯地图：vec cia 或者不传
     * @param key    token值
     *                  天地图需要
     *                  mapbox需要
     */
    imageryProvider(name, { layer, style, key } = {}) {
        let Imagery = null;
        switch (name) {
            case 'amap':
                Imagery = new Cesium.UrlTemplateImageryProvider({
                    url: "http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}",
                })
                this.viewer.imageryLayers.addImageryProvider(Imagery);
                break;

            case 'bmap':
                Imagery = new BmapImageryProvider({ style });
                this.viewer.imageryLayers.addImageryProvider(Imagery);
                break;

            case 'tdt':
                // 如果没有传天地图的token就采用上方定义的
                if (this.Tools.strBool(key)) {
                    let index = Math.floor(Math.random() * this.tdtToken.length)
                    key = this.tdtToken[index]
                }
                Imagery = new Cesium.WebMapTileServiceImageryProvider({
                    url: `http://{s}.tianditu.gov.cn/${layer}/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=${style}&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=${key}`,
                    layer: layer,
                    style: 'default',
                    format: 'tiles',
                    tileMatrixSetID: 'GoogleMapsCompatible',
                    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
                    minimumLevel: 0,
                    maximumLevel: 18,
                })
                this.viewer.imageryLayers.addImageryProvider(Imagery);
                break;

            case 'arcGis':
                Imagery = new Cesium.ArcGisMapServerImageryProvider({
                    url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
                })
                this.viewer.imageryLayers.addImageryProvider(Imagery);
                break;

            case 'naturalEarth':
                Imagery = new Cesium.UrlTemplateImageryProvider({
                    url: Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII') + '/{z}/{x}/{reverseY}.jpg',
                    credit: '© Analytical Graphics, Inc.',
                    tilingScheme: new Cesium.GeographicTilingScheme(),
                    maximumLevel: 5
                })
                this.viewer.imageryLayers.addImageryProvider(Imagery);
                break;

            case 'qqMap':
                Imagery = new Cesium.UrlTemplateImageryProvider({
                    url: 'https://p2.map.gtimg.com/sateTiles/{z}/{sx}/{sy}/{x}_{reverseY}.jpg?version=244',
                    customTags: {
                        sx: function (imageryProvider, x, y, level) {
                            return x >> 4
                        },
                        sy: function (imageryProvider, x, y, level) {
                            return ((1 << level) - y) >> 4
                        }
                    }
                });
                this.viewer.imageryLayers.addImageryProvider(Imagery);

                // 道路及位置标识
                if (style && style.indexOf('vec') > -1) {
                    let qqMapVec = new Cesium.UrlTemplateImageryProvider({
                        url: 'https://rt3.map.gtimg.com/tile?z={z}&x={x}&y={reverseY}&styleid=2&version=859',
                    });
                    this.viewer.imageryLayers.addImageryProvider(qqMapVec);
                }

                // 道路实时情况
                if (style && style.indexOf('cia') > -1) {
                    let qqMapCia = new Cesium.UrlTemplateImageryProvider({
                        url: 'https://rtt2b.map.qq.com/rtt/?z={z}&x={x}&y={reverseY}&times=2&time=1631504424185',
                    });
                    this.viewer.imageryLayers.addImageryProvider(qqMapCia);
                }
                break;

            case 'osm':
                Imagery = new Cesium.OpenStreetMapImageryProvider({
                    url: 'https://a.tile.openstreetmap.org/'
                });
                this.viewer.imageryLayers.addImageryProvider(Imagery);
                break;

            case 'mapbox':
                if (this.Tools.strBool(key)) {
                    key = this.mapboxToken
                }
                Imagery = new Cesium.UrlTemplateImageryProvider({
                    url: `https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/{z}/{x}/{y}?access_token=${key}`
                });
                this.viewer.imageryLayers.addImageryProvider(Imagery);
                break;
        }
        return Imagery
    }
}